<template>
  <Dialog
    v-model="dialogVisible"
    width="80vw"
    maxHeight="70vh"
    :title="t('order.audit')"
    :before-close="() => closeDialog(formRef)"
  >
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="auto">
      <div class="w-full flex justify-between">
        <div class="w-40%">
          <el-form-item :label="t('wholesalOrder.orderNumber')">
            <el-input v-model="form.order_no" disabled placeholder=" " />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.userName')">
            <el-input v-model="form.user_name" disabled placeholder=" " />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.receivingAccountNumber')">
            <el-input v-model="form.pay_account" disabled placeholder=" " />
          </el-form-item>
          <el-form-item :label="t('orderPayment.feeType')">
            <el-input
              :model-value="
                form.fee_type === 1 ? t('orderPayment.orderFee') : t('orderPayment.logisticsFee')
              "
              disabled
            />
          </el-form-item>
          <el-form-item :label="t('orderPayment.transferType')">
            <el-input
              :model-value="useEnumeratePicker(transferTypeList, form.transfer_type)"
              disabled
            />
          </el-form-item>
          <el-form-item :label="t('orderPayment.paymentMethods')" prop="payment_method">
            <el-select
              v-model="form.payment_method"
              :placeholder="t('common.selectText') + t('orderPayment.paymentMethods')"
            >
              <el-option
                v-for="item in payment_methods"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.theAmountToBePaid')" prop="paid_amount">
            <el-input
              v-model="form.paid_amount"
              type="number"
              :placeholder="t('wholesalOrder.theAmountToBePaidMsg')"
            />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.transactionNumber')" prop="voucher_code">
            <el-input
              v-model="form.voucher_code"
              type="text"
              :placeholder="t('wholesalOrder.transactionNumber')"
            />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.proofOfTransfer')">
            <template v-if="form.transfer_voucher_url && form.transfer_voucher_url.length > 0">
              <el-image
                v-for="(imageUrl, index) in form.transfer_voucher_url"
                :key="index"
                style="width: 100px; height: 100px"
                :preview-teleported="true"
                :src="imageUrl"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="form.transfer_voucher_url"
                fit="cover"
              />
            </template>
          </el-form-item>
        </div>
        <div class="w-40%">
          <el-form-item :label="t('wholesalOrder.theTypeOfOrder')">
            <el-input :model-value="useEnumeratePicker(orderTypeList, form.order_type)" disabled />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.paymentTime')">
            <el-input v-model="form.pay_time" disabled />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.notes')">
            <el-input v-model="form.notes" disabled />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.currency')">
            <el-input disabled :model-value="useEnumeratePicker(currencyList, form.currency)" />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.total_amount')">
            <el-input disabled v-model="form.total_amount" />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.unpaid_amount')">
            <el-input disabled v-model="form.unpaid_amount" />
          </el-form-item>
          <el-form-item :label="t('orderPayment.remark')">
            <el-input
              type="textarea"
              v-model="form.remark"
              :placeholder="t('orderPayment.remark')"
            />
          </el-form-item>
          <el-form-item
            :label="t('common.upload') + t('orderPayment.proofOfReceipt')"
            prop="att_path"
            class="w-100%"
          >
            <UploadFile
              url="/common/uploadFile"
              ref="UploadFileRef"
              class="w-100%"
              drag
              multiple
              :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'word', 'txt']"
              :params="{ directory: 20 }"
              :limit="9"
              :upload-file-button-name="t('common.clickUpload')"
              buttonWidth="100%"
              list-type="text"
              :button-link="true"
              :show-file-list="true"
              @upload-success-res="handleUploadCallback"
              @handle-remove-file="handleRemoveFile"
              @handle-picture-card-preview="handlePictureCardPreview"
              :before-upload="handleBeforeUpload"
              @upload-error="handleUploadError"
            />
            <el-text class="mx-1" size="small" type="info">
              {{ t('common.message.uploadExceed', { limit: 9 }) }}
            </el-text>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)" :disabled="uploading"
        >{{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="danger" @click="submit(formRef, false)" :disabled="uploading">{{
        t('common.reject')
      }}</el-button>
      <el-button type="primary" @click="submit(formRef, true)" :disabled="uploading"
        >{{ t('wholesalOrder.approved') }}
      </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from 'element-plus'
import { getEnumApi } from '@/api/wholesalOrder'
import { getPayEnumApi, paymentInformationReviewApi } from '@/api/order/pay'
import { createImageViewer } from '@/components/ImageViewer'

const emit = defineEmits(['refresh'])
const { t } = useI18n()

const dialogVisible = ref<boolean>(false)

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  pay_time: '',
  notes: '',
  transfer_voucher_url: '',
  pay_account: '',
  paid_amount: '',
  currency: '',
  fee_type: 1,
  transfer_recepit_id: [],
  payment_method: 10
})

const paymentMethodList = ref<Array<Record<string, any>>>([])
const currencyList = ref<Array<Record<string, any>>>([])
const orderTypeList = ref<Array<Record<string, any>>>([])
const transferTypeList = ref<Array<Record<string, any>>>([])
const payment_methods = ref<Record<string, any>>()
const rules = ref<FormRules>({
  paid_amount: [
    {
      required: true,
      message: t('wholesalOrder.theAmountToBePaidMsg'),
      trigger: 'blur'
    }
  ],
  payment_method: [
    {
      required: true,
      message: t('common.selectText') + t('orderPayment.paymentMethods'),
      trigger: ['blur', 'change']
    }
  ]
})

const submit = async (formEl: FormInstance | undefined, isApproved: boolean) => {
  if (!formEl) return
  if (!isApproved && !form.value.remark) {
    ElMessage.warning(t('common.inputText') + t('orderPayment.remark'))
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm(t('common.message.operate'), t('common.tip'), {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      })
        .then(async () => {
          const resp = await paymentInformationReviewApi(form.value.id, {
            paid_amount: form.value.paid_amount,
            voucher_code: form.value.voucher_code,
            fee_type: form.value.fee_type,
            is_approved: isApproved,
            remark: form.value.remark,
            transfer_recepit_id: form.value.transfer_recepit_id,
            payment_method: form.value.payment_method
          })
          if (resp.code === 0) {
            ElMessage.success(t('common.operateSucMsg'))
            closeDialog(formEl)
            emit('refresh')
          }
        })
        .catch(() => {})
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  dialogVisible.value = false
}

// 添加上传状态管理
const uploading = ref<boolean>(false)
let uploadingCount = 0

// 检查是否所有文件上传完成
const checkUploadComplete = () => {
  if (uploadingCount <= 0) {
    uploading.value = false
  }
}

// 上传前处理
const handleBeforeUpload = () => {
  // 增加上传计数器
  uploadingCount++
  // 如果是第一个文件，设置上传状态
  if (uploadingCount === 1) {
    uploading.value = true
  }
  return true
}

// 上传错误处理
const handleUploadError = () => {
  // 单个文件上传失败，减少计数器
  uploadingCount--
  checkUploadComplete()
}

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  if (!val) return
  if (val.id) {
    form.value.transfer_recepit_id.push(val.id)
  }

  // 单个文件上传成功，减少计数器
  uploadingCount--
  checkUploadComplete()
}

const handleRemoveFile = (val: any) => {
  if (!val || !val.uid) return
  if (form.value.transfer_recepit_id && form.value.transfer_recepit_id.length) {
    form.value.transfer_recepit_id = form.value.transfer_recepit_id.filter(
      (item: Record<string, any>) => item?.uploadFile?.uid !== val.uid
    )
  }
}

const handlePictureCardPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val],
    zIndex: 3000
  })
}

//根据接口枚举匹配出中文名称
const useEnumeratePicker = (
  enumList: any[],
  field: string | number,
  key?: string,
  value?: string
) => {
  if (!enumList) return
  const matchItem =
    enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
  return matchItem[key ?? 'label'] || ''
}

const getBackShow = async (row: Record<string, any>) => {
  const resp = await getEnumApi({ field: 'all' })
  paymentMethodList.value = resp.data.pay_method
  currencyList.value = resp.data.currency
  const orderResp = await getPayEnumApi({ field: 'all' })
  orderTypeList.value = orderResp.data.order_type
  transferTypeList.value = orderResp.data.transfer_type
  payment_methods.value = orderResp.data.payment_method
  form.value = row
  console.log(row)
  form.value.total_amount = row.order_total_amount
  form.value.unpaid_amount = row.order_total_amount - row.order_pay_amount
  // Ensure transfer_recepit_id is always an array
  if (!form.value.transfer_recepit_id) {
    form.value.transfer_recepit_id = []
  }
}

defineExpose({
  dialogVisible,
  getBackShow
})
</script>
<style lang="less" scoped></style>
